package com.im.util;


import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.text.*;
import java.util.Calendar;

public class GenerateSequenceUtil {

    /** .log */
    private static final Logger logger = LogManager.getLogger(GenerateSequenceUtil.class);

    /** The FieldPosition. */
    private static final FieldPosition HELPER_POSITION = new FieldPosition(0);

    /** This Format for format the data to special format. */
    private final static Format dateFormat = new SimpleDateFormat("yyMMddHHmmss");
    /** SimpleDateFormat("yyMMdd")     */
    private final static Format dateFormat2 = new SimpleDateFormat("yyyyMMdd");
    /** This Format for format the number to special format. */
    private final static NumberFormat numberFormat = new DecimalFormat("00");
    private final static String FillIn = new String("0");
    /** This int is the sequence number ,the default value is 0. */
    private static int seq = 0;

    private static final int MAX = 99;
    private static final int LENGTH = 6;
    /**
     * 时间格式生成序列
     * @return String
     */
    public static synchronized String generateSequenceNo() {

        Calendar rightNow = Calendar.getInstance();

        StringBuffer sb = new StringBuffer();

        dateFormat.format(rightNow.getTime(), sb, HELPER_POSITION);

        numberFormat.format(seq, sb, HELPER_POSITION);

        if (seq == MAX) {
            seq = 0;
        } else {
            seq++;
        }

        logger.info("THE SQUENCE IS :" + sb.toString());

        return sb.toString();
    }
    
    public static synchronized String getLengthSeq() {
    	return getLengthSeq(LENGTH);
    }
    
    public static synchronized String getLengthSeq(int length) {
    	Calendar rightNow = Calendar.getInstance();
        StringBuffer sb = new StringBuffer();
        String dt = dateFormat2.format(rightNow.getTime());
        seq++;
        if(String.valueOf(seq).length()>length){
        	seq = 0;
        }
        sb.append(dt).append(StringUtil.leftFillStr(length,Long.valueOf(seq),FillIn));
        return sb.toString();
    }
    

    
    public static void main(String args[]){
    	GenerateSequenceUtil.generateSequenceNo();
    	GenerateSequenceUtil.getLengthSeq(5);
    }
}